/*
 * Copyright 2009-2015 by WWW.KNET.CN  All rights reserved.
 */
package cn.knet.sp.ncrm.modules.call.config.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cn.knet.sp.ncrm.common.service.CrudService;
import cn.knet.sp.ncrm.common.utils.DateUtils;
import cn.knet.sp.ncrm.modules.call.config.dao.CallConfigDao;
import cn.knet.sp.ncrm.modules.call.config.entity.CallConfig;
import cn.knet.sp.ncrm.modules.call.config.entity.CallConfigType;
import cn.knet.sp.ncrm.modules.sys.dict.entity.Dict;
import cn.knet.sp.ncrm.modules.sys.office.entity.Office;
import cn.knet.sp.ncrm.modules.sys.user.entity.User;
import cn.knet.sp.ncrm.modules.sys.dict.service.DictService;
import cn.knet.sp.ncrm.modules.sys.office.service.OfficeService;
import cn.knet.sp.ncrm.modules.sys.utils.DictUtils;
import cn.knet.sp.ncrm.modules.sys.utils.UserUtils;


/**
 * 查询 和 更新 给定参数信息
 *
 * @author zhangbin
 * @version 2015 /07/07 17:20:09
 */
@Service
public class CallConfigService extends CrudService<CallConfigDao, CallConfig> {

	@Autowired
	private DictService dictService;

	@Autowired
	private OfficeService officeService;

	/**
	 * 根据类型 查询唯一一个参数
	 *
	 * @param type the type
	 * @return the dict from type
	 */
	public Dict getDictFromType(String type) {
		Dict dict = new Dict();
		dict.setType(type);
		List<Dict> dictList = DictUtils.getDictList(type);
		if (dictList.size() > 0) {
			return dictList.get(0);
		}
		return null;
	}

	/**
	 * 更新数据字典的一个值
	 * @author zhangbin
	 * @date 2015 /07/09 16:10:58
	 * @param type the type
	 * @param value the value
	 */
	@Transactional
	private void updateDictFromType(String type, String value) {
		Dict dict = getDictFromType(type);
		Dict updatDict = new Dict();
		if (dict == null) {
			updatDict.setLabel(type);
			updatDict.setSort(99);
		} else {
			updatDict.setLabel(dict.getLabel());
			updatDict.setDescription(dict.getDescription());
			updatDict.setSort(dict.getSort());
		}
		updatDict.setId(dict.getId());
		updatDict.setValue(value);
		updatDict.setType(type);
		dictService.save(updatDict);
	}

	/**
	 * 更新班次的4个值 用事务控制
	 *
	 * @param ws11 上午 上班
	 * @param ws12 上午 下班
	 * @param ws21 下午 上班
	 * @param ws22 下午 下班
	 * @author zhangbin
	 * @date 2015 /07/08 13:38:46
	 */
	@Transactional
	public void updateWorkShifts(String ws11, String ws12, String ws21, String ws22) {
		updateDictFromType("CALL_CONFIG_SHIFT1_START", ws11);
		updateDictFromType("CALL_CONFIG_SHIFT1_END", ws12);
		updateDictFromType("CALL_CONFIG_SHIFT2_START", ws21);
		updateDictFromType("CALL_CONFIG_SHIFT2_END", ws22);
	}

	public void updateWorkEndingTime(String workEndingTime) {
		updateDictFromType("CALL_CONFIG_ENDING_TIME", workEndingTime);
	}

	/**
	 * 更新 时间的配置信息
	 * @author zhangbin
	 * @date 2015 /07/09 16:10:01
	 * @param longCalling the long calling
	 * @param timeOutCalling the time out calling
	 */
	@Transactional
	public void updateCalling(Integer longCalling, Integer timeOutCalling) {
		updateDictFromType("CALL_CONFIG_LONG_CALLING_TIME", String.valueOf(longCalling));
		updateDictFromType("CALL_CONFIG_TIME_OUT_TIME", String.valueOf(timeOutCalling));
	}

	/**
	 * 更新最短接听时间
	 * @author zhangbin
	 * @date 2015 /07/09 16:10:17
	 * @param rate the rate
	 */
	@Transactional
	public void updateRate(Integer rate) {
		updateDictFromType("CALL_CONFIG_RING_LENGTH", String.valueOf(rate));
	}

	/**
	 * 执行存储过程,重新统计当天信息
	 * @author zhangbin
	 * @date 2015 /07/09 16:10:36
	 */
	@Transactional
	public void executeStat() {
		dao.executeStat();
	}

	public Map<String, String> listOffice() {
		User user = UserUtils.getUser();
		Map<String, String> offices = new LinkedHashMap<String, String>();
		Office entity = new Office();
		if ("1".equals(user.getUserType())) { //如果是系统管理员
			entity.setParentIds("0,1,%");
		} else if ("2".equals(user.getUserType())) {
			entity = UserUtils.getUser().getOffice();
		} else {
			Office queryEntity = UserUtils.getUser().getOffice();
			entity.setParentIds(queryEntity.getParentIds() + queryEntity.getId() + ",");
		}
		List<Office> officeList = officeService.findList(entity);
		for (Office office : officeList) {
			offices.put(office.getId(), office.getName());
		}
		return offices;
	}

	private String createPriex(String s, String parentIds) {
		int size = parentIds.split(",").length;
		StringBuffer sb = new StringBuffer();
		for (int i = 2; i < size; i++) {
			sb.append(s);
		}
		return sb.toString();
	}

	/**
	 * 更新组织机构设置的 数据字典
	 * @author zhangbin
	 * @date 2015 /07/09 16:09:40
	 * @param set the set
	 * @param type the type
	 */
	@Transactional
	public void updateGroups(Set<String> set, CallConfigType type) {
		String dictType = "CALL_CONFIG_OFFICE_IN";
		if (CallConfigType.OUTGROUP.equals(type)) {
			dictType = "CALL_CONFIG_OFFICE_OUT";
		}
		List<Dict> delDicts = DictUtils.getDictList(dictType);
		List<Dict> updateDicts = new ArrayList<Dict>();
		List<Dict> insertDicts = new ArrayList<Dict>();
		int index = 1;
		for (String officeId : set) {
			Office office = officeService.get(officeId);
			if (office != null) {
				if (delDicts.size() > 0) {
					Dict first = delDicts.get(0);
					first.setLabel(office.getName());
					first.setValue(office.getId());
					first.setSort(index);
					first.setDescription("呼叫中心配置_" + office.getName());
					updateDicts.add(first);
					delDicts.remove(0);
				} else {
					Dict dict = new Dict();
					dict.setLabel(office.getName());
					dict.setValue(office.getId());
					dict.setDescription("呼叫中心配置_" + office.getName());
					dict.setType(dictType);
					dict.setSort(index);
					insertDicts.add(dict);
				}
			}
			index++;
		}
		for (Dict dict : delDicts) {
			dictService.delete(dict);
		}
		for (Dict dict : updateDicts) {
			dictService.save(dict);
		}
		for (Dict dict : insertDicts) {
			dictService.save(dict);
		}
	}

	/**
	 * 转换Dict对象为整形 吃掉异常
	 * @author zhangbin
	 * @date 2015 /07/09 16:08:25
	 * @param number the number
	 * @return the integer
	 */
	private Integer initNumber(Dict number) {
		if (number != null) {
			try {
				return Integer.valueOf(number.getValue());
			} catch (NumberFormatException e) {
				logger.warn("数据字典错误-整形类型转换失败");
				return null;
			}
		}
		return null;
	}

	/**
	 * 转换为规定的日期类型 吃掉异常
	 * @author zhangbin
	 * @date 2015 /07/09 16:08:49
	 * @param workShift the work shift
	 * @return the string
	 */
	private String initWorkShift(Dict workShift) {
		if (workShift != null) {
			Date date = null;
			try {
				date = DateUtils.parseDate(workShift.getValue(), "HHmmss");
				return DateUtils.formatDate(date, "HH:mm:ss");
			} catch (ParseException e) {
				logger.warn("数据字典错误-转换日期类型失败");
				return null;
			}

		}
		return null;
	}

	/**
	 * 初始化CallConfig对象
	 * @author zhangbin
	 * @date 2015 /07/09 16:04:06
	 */
	public void initCallConfig(CallConfig callConfig) {
		callConfig.setWorkShift1start(initWorkShift(getDictFromType("CALL_CONFIG_SHIFT1_START")));
		callConfig.setWorkShift1end(initWorkShift(getDictFromType("CALL_CONFIG_SHIFT1_END")));
		callConfig.setWorkShift2start(initWorkShift(getDictFromType("CALL_CONFIG_SHIFT2_START")));
		callConfig.setWorkShift2end(initWorkShift(getDictFromType("CALL_CONFIG_SHIFT2_END")));
		callConfig.setWorkEndTime(initWorkShift(getDictFromType("CALL_CONFIG_ENDING_TIME")));
		callConfig.setLongCallSec(initNumber(getDictFromType("CALL_CONFIG_LONG_CALLING_TIME")));
		callConfig.setTimeOutSec(initNumber(getDictFromType("CALL_CONFIG_TIME_OUT_TIME")));
		callConfig.setQuickRingSec(initNumber(getDictFromType("CALL_CONFIG_RING_LENGTH")));
		List<Dict> outDicts = DictUtils.getDictList("CALL_CONFIG_OFFICE_OUT");
		List<Dict> inDicts = DictUtils.getDictList("CALL_CONFIG_OFFICE_IN");
		Map<String, String> outMap = new LinkedHashMap<String, String>();
		Map<String, String> inMap = new LinkedHashMap<String, String>();
		for (Dict dict : outDicts) {
			outMap.put(dict.getValue(), dict.getLabel());
		}
		for (Dict dict : inDicts) {
			inMap.put(dict.getValue(), dict.getLabel());
		}
		Map<String, String> outAllMap = listOffice();
		Map<String, String> inAllMap = new HashMap<String, String>(outAllMap);
		for (String key : outMap.keySet()) {
			outAllMap.remove(key);
		}
		for (String key : inMap.keySet()) {
			inAllMap.remove(key);
		}
		callConfig.setInAllGroups(inAllMap);
		callConfig.setOutAllGroups(outAllMap);
		callConfig.setInGroups(inMap);
		callConfig.setOutGroups(outMap);
	}

}
